package com.pagoda.nerp.trade.admin.system.web;

import com.pagoda.nerp.trade.admin.vendor.common.ParameterChecking;
import com.pagoda.nerp.trade.common.BaseResult;
import com.pagoda.nerp.trade.common.enums.ErrorCodeMappingEnums;
import com.pagoda.nerp.trade.common.exception.AccountException;
import com.pagoda.nerp.trade.entity.AccUsers;
import com.pagoda.nerp.trade.service.AccUsersService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * Created by Jungle on 2016/12/16.
 */
@Controller
@RequestMapping("/systemmgr")
public class AccUserCtr {

    private static final Logger logger = LoggerFactory.getLogger(AccUserCtr.class);

    @Autowired
    private AccUsersService accUsersService;

    /**
     * 登录
     * @param params 请求参数
     * @return 返回响应结果 - 由前端控制页面跳转
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST,
                    produces = "application/json;charset=UTF-8")
    @ResponseBody
    public BaseResult login(@RequestBody Map params, HttpServletRequest httpServletRequest) {

        try {
            // 1、校验参数有效性
            String checkResult = ParameterChecking.loginChk(params);
            if(null != checkResult && !"".equals(checkResult)){
                logger.debug("请求参数缺失，请求信息:{}",checkResult);
                return new BaseResult(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS,checkResult);
            }

            AccUsers accUsers = accUsersService.findAccUsersByCondition(params);
            String userCode = accUsers.getUserCode();

            // 保存会话信息
            HttpSession httpSession = httpServletRequest.getSession();
            httpSession.setAttribute("userCode", userCode);
            return new BaseResult<AccUsers>(ErrorCodeMappingEnums.SUCCESS, accUsers);

        }catch (AccountException ae){
            logger.error("Controller 登录失败!",ae);
            return new BaseResult(ErrorCodeMappingEnums.ERROR_INVALID_ACCOUNT);
        }catch(Exception e){
            logger.error("Controller执行登录异常!",e);
            return new BaseResult(ErrorCodeMappingEnums.ERROR);
        }
    }

    /**
     * 登出
     * @param params 请求参数
     * @return 返回响应结果 - 登出页面跳转由前端进行过控制
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST,
                    produces = "application/json;charset=UTF-8")
    @ResponseBody
    public BaseResult<List> logout(@RequestBody Map params,HttpServletRequest httpServletRequest) {
        HttpSession httpSession = httpServletRequest.getSession();
        httpSession.invalidate();
        return new BaseResult(ErrorCodeMappingEnums.SUCCESS);
    }

    @RequestMapping(value = "/loginShiro", method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @ResponseBody
    public BaseResult loginShiro(@RequestBody Map params, HttpServletRequest httpServletRequest) {
        try {
            // 1、校验参数有效性
            String checkResult = ParameterChecking.loginChk(params);
            if(null != checkResult && !"".equals(checkResult)){
                logger.debug("请求参数缺失，请求信息:{}",checkResult);
                return new BaseResult(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS,checkResult);
            }
            String userCode = params.get("userCode").toString();
            String password = params.get("password").toString();
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(userCode, password);
            token.setRememberMe(true);
            subject.login(token);
            if (subject.isAuthenticated()) {
                subject.getSession().setAttribute("h5ShiroAuthentication",token);
                return new BaseResult<AccUsers>(ErrorCodeMappingEnums.SUCCESS);
            } else {
                return new BaseResult(ErrorCodeMappingEnums.ERROR_INVALID_ACCOUNT);
            }
        }catch (AuthenticationException ae){
            logger.error("Controller 登录失败!",ae);
            return new BaseResult(ErrorCodeMappingEnums.ERROR_INVALID_ACCOUNT);
        }catch(Exception e){
            logger.error("Controller执行登录异常!",e);
            return new BaseResult(ErrorCodeMappingEnums.ERROR);
        }
    }
}
